<template>
<div class="bbx-normal-page-content" v-loading="pageLoading">
  <div v-if="serviceStationEnabled" ref="eventPageRef" class="event-list common-list-container__v2">
    <!-- 头部块 -->
    <div ref="tableHeaderContainer" class="list-header">
      <div class="list-header-search bg-w">
        <div class="custom-view"></div>
        <div class="right-view">
          <form onsubmit="return false;">
            <div class="searh-input-box"> 
              <!-- 输入框搜索/重置 -->
              <div class="base-search-group input-with-append-search mar-r-24">
                <el-input v-model="searchParams.keyword" :placeholder="$t('event.eventOrderList.text3')" class="task-mr12 search-input">
                  <i slot="prefix" class="el-input__icon el-icon-search"></i>
                  <el-button 
                    type="primary"
                    slot="append"
                    @click="searchParams.pageNum = 1; search();"
                    native-type="submit"
										v-track="$track.formatParams('KEYWORD_SEARCH')">
                    {{$t('common.base.search')}}
                  </el-button>
                </el-input>
                <el-button type="plain-third" @click="resetParams" v-track="$track.formatParams('RESET_SEARCH')">{{$t('common.base.reset')}}</el-button>
              </div>
              <!-- 高级搜索 -->
              <div class="advanced-search-btn pointer" @click.self.stop="panelSearchAdvancedToggle">
                <i class="iconfont icon-filter"></i>
                {{$t('common.base.advancedSearch')}}
              </div>
            </div>
          </form>
        </div>
      </div>
      <div class="list-header-nav bg-w" v-show="packUp">
        <div class="filter-tab-box filter-tab">
          <div class="filter-tab__item" v-for="(item, index) in filterConfig" :key="index">
            <div class="filter-tab__label">{{ item.label }}：</div>
            <div :class="['filter-tab__content', item.name === 'templateId' ? 'filter-tab__content-pad' : null ]" :style="item.name === 'templateId' ? stateHeight:''">
              <div class="content-item" v-for="(cItem, cIndex) in item.content" :key="cIndex" @click="handleFilterClick(item, cItem)">
                <!-- 异常事件 -->
                <el-tooltip
                  v-if="cItem.value == 'exception' && abnormalText"
                  :content="`${abnormalText}`"
                  placement="top"
                >
                  <span
                    :class="['content-item-label', {'actived': cItem.active === true}, 'task-cef']"
                    :title="cItem.label">
                    {{ cItem.label }} {{cItem.count ? `(${cItem.count})` : item.name === 'state' ? '(0)' : ''}}
                  </span>
                </el-tooltip>
                <!-- 异常事件 -->
                <span
                  v-else
                  :class="['content-item-label', {'actived': cItem.active === true}, {'task-cef': cItem.value == 'exception'}]"
                  :title="cItem.label">
                  {{ cItem.label }} {{cItem.count ? `(${cItem.count})` : item.name === 'state' ? '(0)' : ''}}
                </span>
              </div>
              <div
                class="element-icon more-icon"
                v-if="item.name === 'templateId' && item.content.length * 130 > navWidth"
                @click="
                  (stateHeight =
                    stateHeight === `height:30px` ? `height:auto` : `height:30px`),knowTableContainerHeight()
                "
              >
                <span v-if="stateHeight === 'height:30px'">
                  {{$t('common.base.more')}}
                  <i class="iconfont icon-fdn-select task-icon"></i>
                </span>
                <i class="el-icon-arrow-up task-icon" v-else></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 开/关按钮 -->
      <div class="bbx-normal-pack-up">
          <div @click="changePackUp()">
            <i class="iconfont icon-Icon_up" v-show="packUp"></i>
            <i class="iconfont icon-more" v-show="!packUp"></i>
          </div>
      </div>
    </div>

    <!-- 主内容块 -->
    <div class="common-list-view__v2">
      <div ref="tableDoContainer" class="operate-box">
        <div class="operate-box__left">
          <!-- 新建 -->
          <el-dropdown v-if="CASE_ADD">
            <el-button type="primary" icon="el-icon-plus">{{$t('common.base.create')}}</el-button>
            <el-dropdown-menu slot="dropdown">
              <div class="event-type-dropdown-group">
                <el-dropdown-item v-for="(item, index) in createTypeList" :key="index">
                  <div @click="toCreateEvent(item)">{{ item.name }}</div>
                </el-dropdown-item>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- 批量编辑 -->
          <el-button type="plain-third" v-if="editAll" class="ml_12" @click="handleAllotEdit" v-track="$track.formatParams('BATCH_EDIT')">
            <i class="iconfont icon-edit-square task-font14"></i>
            {{$t('common.base.bulkEdit')}}
          </el-button>
          <!-- 删除 -->
          <el-button type="plain-third" v-if="CASE_DELETE && editAll" class="ml_12" @click="handleDelete" v-track="$track.formatParams('DELETE')">
            <i class="iconfont icon-delete task-font14"></i>
            {{$t('common.base.delete')}}
          </el-button>
        </div>
        <div class="operate-box__right action-button-group">
          <el-tooltip v-if="searchParams.state === 'created'" :content="$t('event.eventOrderList.text4')">
            <i
              class="iconfont icon-ding-yue pointer task-icon"
              :class="hasSub ? 'actived' : ''"
              @click="toggleEventSubscribe">
              {{ hasSub ? $t('common.base.subscribed'): $t('common.base.notSubscribed')}}
            </i>
          </el-tooltip>
          <!-- 更多操作 -->
          <el-dropdown v-if="exportIn || batchTransferEvent || canImportEvent" trigger="click">
            <div class="cur-point">
              <span>{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="isButtonDisplayed && !isExperienceEdition && canImportEvent">
                <div class="import-event">
                  {{$t('common.base.importEvent')}}
                  <div class="import-event-item import-item">
                    <div v-for="(item, index) in initData.eventTypeList" :key="index">
                      <span>{{ item.name }}</span>
                      <div class="import-event-item-children import-item-children" v-track="$track.formatParams('IMPORT_EVENT', null, 'MORE_ACTIONS')">
                        <div @click="importEvent(item, true)">{{$t('event.list.text2')}}</div>
                        <div @click="importEvent(item, false)">{{$t('event.list.text3')}}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-dropdown-item>
              <el-dropdown-item v-if="isButtonDisplayed && allowExport">
                <div @click="handleExport(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="isButtonDisplayed && allowExport">
                <div @click="handleExport(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="allowExport">
                <!-- 附件下载 -->
                <div @click="exportAttachment" v-track="$track.formatParams('DOWNLOAD_ATTACHMENT', null, 'MORE_ACTIONS')">{{$t('common.base.downloadAttachment')}}</div>
              </el-dropdown-item>
              <!-- 批量转交 -->
              <el-dropdown-item v-if="batchTransferEvent">
                <div @click="handleEventReAllot" v-track="$track.formatParams('EVENT_REALLOT', null, 'MORE_ACTIONS')">{{$t('event.eventOrderList.text2')}}</div>
              </el-dropdown-item>
              <!-- start 批量导出附加组件 -->
              <el-dropdown-item v-if="showExportAdditional">
                <div class="import-event">
                  {{$t('common.base.BatchExport')}}
                  <div class="import-event-item import-item batch-export-additional">
                    <div v-for="(item, index) in eventCardList" :key="index">
                      <span @click="exportAdditional(item)">{{ item.name }}</span>
                    </div>
                  </div>
                </div>
              </el-dropdown-item>
              <!-- end 批量导出附加组件 -->
            </el-dropdown-menu>
          </el-dropdown>

          <!-- 选择列 -->
          <div class="guide-box">
            <div :class="['task-pointer', 'cur-point']" @click="showAdvancedSetting" v-track="$track.formatParams('SELECT_COLUMN')">
              <span>{{$t('common.base.choiceCol')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
          </div>
        </div>
      </div>
      
      <!-- <div v-show="multipleSelection.length" class="common-list-selection__v2 mt_8">
        已选择
        <span>{{ multipleSelection.length }}</span>条
        <span class="pointer" @click="toggleClearSelection">清空</span>
      </div> -->
      
      <!-- 表格 -->
      <el-table
        v-if="columns.length"
        ref="table"
        class="mt_12 bbx-normal-list-box"
        stripe
        :key="tableKey"
        :row-key="getRowKey"
        :data="eventPage.list || []"
        :highlight-current-row="false"
        :border="true"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        @header-dragend="headerDragend"
        v-loading="loading"
        header-row-class-name="common-list-table-header__v2"
        :height="tableContainerHeight"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!loading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
        </template>
        <el-table-column
          type="selection"
          width="48"
          align="center"
          class-name="select-column"
          :reserve-selection="true"
        ></el-table-column>
        <template v-for="column in columns">
          <el-table-column
              v-if="column && column.show"
              :show-overflow-tooltip="getCommonListShowTooltip(column)"
              :align="column.align"
              :key="column.field"
              :label="column.displayName"
              :min-width="column.minWidth"
              :prop="column.field"
              :sortable="column.sortable"
              :width="column.width"
              :resizable="true"
              :fixed="column.fixLeft || false"
            >
              <template slot-scope="scope">
                <!-- 处理示例数据 -->
                <template v-if="column.field === 'eventNo'">
                  <sample-tooltip :row="scope.row">
                    <template slot="content" slot-scope="{isContentTooltip}">
                      <el-tooltip
                        :content="scope.row[column.field]"
                        placement="top"
                        :disabled="!isContentTooltip"
                      >
                        <div>
                          <span :class="[allowEventViewDetail ? 'view-detail-btn' : 'view-detail-btn-disabled']" class="task-list-numbering"
                            @click="openEventDetailTab(scope.row.id, scope.row.eventNo)">
                            {{ scope.row[column.field] }}
                          </span>
                          <span v-if="scope.row.inApprove == 1" 
                            class="task-state-block__v2 task-state-block__v2-approve task-font12">
                            {{$t('common.event.approveStatus.approve')}}
                          </span>
                          <span v-if="scope.row.isOverTime == 1"
                            class="task-state-block__v2 task-state-block__v2-overtime task-font12">
                            {{$t('common.event.exceptionStatus.overTime')}}
                          </span>
                        </div>
                      </el-tooltip>
                    </template>
                  </sample-tooltip>
                </template>
                <template v-else-if="column.renderCell">
                  <base-table-cell :render-cell="column.renderCell" :column="column" :row="scope.row"></base-table-cell>
                </template>
                <template v-else-if="column.formType === 'connector'">
                  <div v-if="scope.row.attribute && scope.row.attribute[column.field]" class="view-detail-btn task-client" @click.stop="openConnectorDialog(column, scope.row)">
                    {{ $t('common.base.view') }}
                  </div>
                </template>
                <template v-else-if="column.isSystem === 1">
                  {{ $formatFormField(column, scope.row) }}
                </template>
                
                <template v-else-if="column.formType === 'relationCustomer' && scope.row.attribute[column.field] && column.setting && (column.setting.formType === 'user' || column.setting.fieldName === 'customerManager')">
                  <template v-if="isOpenData">
                    <open-data v-for="staffId in getUserIds(scope.row.attribute[column.field])" :key="staffId" type="userName" :openid="staffId"></open-data>
                  </template>
                  <template v-else>
                    {{ getUserName(scope.row.attribute[column.field]) }}
                  </template>
                </template>
                
                <template v-else-if="column.formType === 'logistics'">
                  <biz-list-logistics-no
                    :row="scope.row"
                    :column="column"
                    :is-link="isCanLogisticsNoLink(column)"
                    mode="event"
                    :biz-id="scope.row.id"
                  />
                </template>
                
                <template v-else-if="column.formType === 'user' && scope.row.attribute[column.field]">
                  <template v-if="isOpenData">
                    <open-data v-for="staffId in getUserIds(scope.row.attribute[column.field])" :key="staffId" type="userName" :openid="staffId"></open-data>
                  </template>
                  <template v-else>
                    {{ getUserName(scope.row.attribute[column.field]) }}
                  </template>
                </template>

                <template v-else-if="['relationCustomer', 'relationProduct'].includes(column.formType) && (column.setting || {}).formType === 'cascader'">
                  {{ (scope.row.attribute[column.field]) | fmt_form_cascader((column.setting || {}).isMulti, (column.setting || {}).displayMode)}}
                </template>

                <template v-else-if="column.formType === 'phone'">
                  <div>
                    {{ scope.row.attribute[column.field] }}
                    <i 
                      v-if="hasCallAuth && callCenterModule && scope.row.attribute[column.field]"
                      class="iconfont icon-fdn-phone color-primary cur-point"
                      title="拨打电话" 
                      @click="makePhoneCall(scope.row.attribute[column.field])"
                    ></i>
                  </div>
                </template>
                <!-- 富文本 -->
                <template v-else-if="column.formType === 'richtext'">
                  <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
                    <span v-if="scope.row.attribute && scope.row.attribute[column.field]">{{$t('common.base.view')}}</span>
                  </div>
                </template>
                <template v-else>
                  {{ $formatFormField(column, scope.row) }}
                </template>
                
              </template>
          </el-table-column>
        </template>
      </el-table>
      
      <!-- 分页信息 -->
      <div ref="tableFooterContainer" class="table-footer  bbx-normal-table-footer-12 pad-b-16 bg-w pad-t-16">
        <div class="list-info" >
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{ eventPage.total || 0 }}</span>
          </i18n>
          <template v-if="multipleSelection&&multipleSelection.length>0">
            <i18n path="common.base.table.selectedNth">
              <span
                place="count"
                class="color-primary pad-l-5 pad-r-5"
              >{{ multipleSelection.length }}</span>
            </i18n>
            <span class="color-primary cur-point" @click="toggleClearSelection">{{$t('common.base.clear')}}</span>
          </template>
        </div>
        <el-pagination
          class="product-template-table-pagination"
          background
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="eventPage.total"
        >
        </el-pagination>
      </div>

      <!-- 高级搜索框 -->
      <base-search-drawer
        :show.sync="visible"
        :storage-key="advancedColumnNumStorageKey"
        @reset="resetParams"
        @search="search"
        @changeWidth="setAdvanceSearchColumn"
        @getColumnNum="setAdvanceSearchColumn"
      >
        <base-search-panel ref="searchPanel" :column-num="columnNum" :fields="advanceSearchColumn"/>
      </base-search-drawer>

      <!-- 批量编辑 -->
      <event-batch-edit-dialog
        ref="eventBatchEditDialog"
        :config="{
          fields: batchEditEventTemplateFields,
          currentEventType: currentEventType,
          type: 'notOrder'
        }"
        :selected-ids="selectedIds"
        :select-list='multipleSelection'
        @update="updateEdit"
      ></event-batch-edit-dialog>

      <!-- 导出工单 -->
      <base-export-group
        ref="exportPanel"
        :storage-key="eventTypeExportStorageKey"
        :alert="exportAlert"
        :columns="exportColumnList"
        :build-params="buildExportParams"
        :group="true"
        :validate="checkExportCount"
        method="post"
        :action="eventListExport"
        :is-show-export-tip="isOpenData"
      />

      <!-- 导入事件 -->
      <base-import
        :title="`${$t('common.base.importEvent')}-${checkedImportEvent.name}-${eventImportExist ? $t('event.list.text5') : $t('event.list.text6')}`"
        ref="importCustomerModal"
        :action="eventImportAction"
        :template-url="eventImportTemplateUrl"
      >
      </base-import>

      <!-- 选择列 --> 
      <biz-select-column ref="advanced" @save="saveColumnStatus" />

      <!-- 事件转发弹窗 -->
      <event-batch-reallot-dialog ref="eventBatchReAllotDialog" :event-id-list="selectedIds"></event-batch-reallot-dialog>

      <!-- 连接器明细弹窗 -->
      <connector-table-dialog ref="connectorDialogRef" />
    </div>
  </div>

  <statistical-dialog ref="statistical" :use-export-url="false" />
  <!--查看富文本 -->
  <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
</div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform'
import AuthUtil from '@src/util/auth';
import * as EventApi from '@src/api/EventApi.js';
import { pageEventList } from 'pub-bbx-global/pageType/dist';
import Page from '@model/Page';
import {getColumnFields, getAdvancedFields, getFilterConfig, getExceptionFields, getExportSystemInfo} from './fields';
import { checkButtonDisplayed } from '@src/util/dom';

import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import EventBatchReAllotDialog from '../components/EventBatchReAllotDialog';
import EventBatchEditDialog from '../components/EventBatchEditDialog.vue';
import statisticalDialog from '@src/modules/setting/serviceEvent/additional/components/statisticalDialog.vue'

import { storageGet, storageSet } from "@src/util/storage";
import {sessionStorageGet, sessionStorageRemove} from "@src/util/storageV2";
import _ from "lodash";
/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts'
/* export & import */
import { eventListExport } from '@src/api/Export';
import { eventListImport_1, eventListImportTem_1 } from '@src/api/Import';
/* mixin */
import VersionMixin from '@src/mixins/versionMixin/index.ts'
/* service */
import { smoothLogisticsField } from '@service/LogisticsService'
import { getFieldWithFieldName } from '@service/FieldService'
import { EventFieldNameMappingEnum, FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum'
/* util */
import { formatDate, useFormTimezone } from 'pub-bbx-utils'
import { defaultTableData } from '@src/util/table'
const { disposeFormListViewTime } = useFormTimezone()
import { showExportListAlert } from '@src/util/alert';
/* mixin */
import EventListMixin from 'src/modules/event/eventList/event-list-mixin.js'


const EVENT_LIST_KEY = 'event_list';
const EVENT_PAGE_SIZE_KEY = 'event_page_size';
const MAXCHECK = 500
import { safeNewDate } from '@src/util/time';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

import { setServerCach, getServerCach } from '@src/util/serverCach'
import { cloneDeep } from 'lodash';

export default {
  mixins: [
    VersionMixin,
    EventListMixin,
  ],
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [EventBatchReAllotDialog.name]: EventBatchReAllotDialog,
    [EventBatchEditDialog.name]: EventBatchEditDialog,
    [statisticalDialog.name]: statisticalDialog,
  },
  data() {
    return{
      defaultTableData,
      showHeaderNav: true,
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      searchParams: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
        orderDetail: {}
      },
      tableKey: Math.random() * 1000 >> 2,
      filterConfig: [],
      abnormalText: '', // 异常节点
      extraAdvanceFields: [],
      eventTemplateFields: [], // 事件类型字段
      eventTemplateReceiptFields: [], // 事件类型回执字段
      currentEventType: {}, // 当前事件类型
      currentEventStatus: {}, // 当前事件状态
      multipleSelection: [],

      eventPage: new Page(),
      visible: false,
      columns: [],
      columnNum: 1,

      checkedImportEvent:{},
      eventImportExist: null, // 现有客户true/非现有客户false
      eventImportAction: '',
      eventImportTemplateUrl: '',
      exportColumnList:[],

      navWidth: window.innerWidth - 120,
      isFold: false,
      stateHeight: '',
      loading: false,
      hasSub: 1,
      advancedColumnNumStorageKey: StorageKeyEnum.EventListAdvancedColumnNum,
      exportStorageKey: StorageKeyEnum.EventListExport,
      eventListExport,
      eventPlanningBtn: false,
      satisfactionFields: [],
      tableContainerHeight:'440px',
      packUp:true,
      pageLoading:false,
      originAllFields:[],
      eventTypeObj: {},
      // 批量导出附加组件 Start
      eventCardList: [],
      // 批量导出附加组件 End
      isFetchEventPageEnd: false,
      originEventPage: {},
      allCustomFields: [],
    }
  },
  watch: {

    // eventImportExist(value) {
    //   this.eventImportAction = `${eventListImport_1}/${value ? 'exist' : 'notExist' }?typeId=${this.checkedImportEvent.id}`
    //   this.eventImportTemplateUrl = `${eventListImportTem_1}?way=${value ? '1' : '2' }&typeId=${this.checkedImportEvent.id}`
    // },
  },
  computed: {
    showColumns() {
      return this.columns.filter(item => item.show);
    },
    EVENT_COLUMNS_KEY() {
      // 根据不同事件类型&不同事件状态返回不同的选择列存储key值
      const eventTypeKey = this.currentEventType?.id ? this.currentEventType.id : 'all'
      const eventStatusKey = this.currentEventStatus?.value ? this.currentEventStatus?.value : 'all'
      const key = `eventColumns_status-${eventStatusKey}_type-${eventTypeKey}`
      return key
    },
    // 高级搜索字段
    advanceSearchColumn() {
      let fields = getAdvancedFields(this);
      if(!this.eventPlanningBtn){
        fields = fields.filter(x=>{
          return x.fieldName != 'planStartTime' && x.fieldName != 'planEndTime';
        })
      }

      fields = fields.filter(field => {

        if (field.fieldName == 'taskNo') {
          return this._isShowTaskModule;
        }

        return true;

      })

      return [
        ...fields,
        ...this.extraAdvanceFields
      ].filter(item => 
        item.isSearch && item.isSearch == 1 && item.show !== false
      );
    },

    // 当前选中的工单ids
    selectedIds() {
      return this.multipleSelection.map((p) => p.id);
    },

    /** 事件类型过滤后的字段 */
    eventTypeFilterFields() {
      let fields = []
      // 没有选择某个事件类型的时候，点击全部，获取所有事件类型的自定义字段
      if(!this.currentEventType?.id) {
        fields = this.allCustomFields;
      }else {
        fields = this.eventTemplateFields.concat(this.eventTemplateReceiptFields) || [];
      }
      
      let eventTypeFilterFields = fields.filter((field) => {
        return (
          ['attachment', 'autograph'].indexOf(field.formType) == -1
          && field.isSystem == 0
        )
      });
      return eventTypeFilterFields;
    },
    eventListFieldsMap() {
      return this.eventTemplateFields.reduce((map, field) => {
        map[field.fieldName] = field;
        return map;
      }, {});
    },
    /** 事件列表字段 */
    eventListFields() {
      let columnFields = getColumnFields(this);
      // 如果开启客户满意度过滤掉满意度、服务标签、客户评价
      if(this.customerSatisfaction) {
        columnFields = columnFields.filter(f=>{
          return f.fieldName != 'tagEvaluates' && f.fieldName != 'eventSuggestion' && f.fieldName != 'eventDegree';
        })
      }

      const taskRelevantFieldNames = [
        'isEventRelevance',
        'isTransferToTask',
      ]

      columnFields = columnFields.filter(field => {

        if (taskRelevantFieldNames.includes(field.fieldName)) {
          return this._isShowTaskModule;
        }

        return true;

      })
      
      if(!this.eventPlanningBtn){
        columnFields = columnFields.filter(x=>{
          return x.sortName != 'planStartTime' && x.sortName != 'planEndTime';
        })
      }
      
      return []
        .concat(columnFields)
        .filter((f) => f.formType !== 'separator' && f.formType !== 'info')
        .map((field) => {
          
          if (field.sortName == 'planStartTime' || field.sortName == 'planEndTime') {
            const serverField = this.eventListFieldsMap[field.sortName];
            return {
              ...field,
              ...serverField
            }
          }

          return field;
          
        })
        .sort((a, b) => a.orderId - b.orderId);
    },
    editAll() {
      return this.initData.editAll || false
    },
    // 事件批量转交权限
    batchTransferEvent() {
      return this.initData.batchTransferEvent || false
    },
    // 是否显示批量导出附加组件
    showExportAdditional() {
      return this.isButtonDisplayed && this.allowExport && !this.currentEventType.id
    },
    exportIn() {
      return this.allowExport || this.allowImport
    },
    allowExport() {
      return Boolean(this.initData?.export)
    },
    allowImport() {
      return Boolean(this.initData?.import)
    },
    canImportEvent() {
      return AuthUtil.hasAuth(this.auth, 'CASE_IMPORT') && this.CASE_ADD
    },
    serviceStationEnabled() {
      return this.initData.serviceStationEnabled || false
    },
    CASE_ADD() {
      return AuthUtil.hasAuth(this.auth, 'CASE_ADD')
    },
    CASE_DELETE() {
      return AuthUtil.hasAuth(this.auth, 'CASE_DELETE')
    },
    customerField() {
      return getFieldWithFieldName(this.eventTemplateFields || [], EventFieldNameMappingEnum.Customer)
    },

    batchEditEventTemplateFields() {
      const eventTemplateFields = [...this.eventTemplateFields]; 

      if(this.editAll){
        const synergiesField = {
          displayName: this.$t('common.fields.synergies.displayName'),
          fieldName: 'synergies',
          formType: 'user',
          enabled: 1,
          isNull: 1,
          setting: {
            isMultiple: 1
          }
        }
        eventTemplateFields.unshift(synergiesField)
      }
      return eventTemplateFields.filter(field => field.formType !== 'logistics' && field.formType !== 'richtext');
    },
    eventTypeExportStorageKey() {
      return this.currentEventType?.id ? `${this.exportStorageKey}_${this.currentEventType.id}` : this.exportStorageKey;
    },
    createTypeList() {
      return this.eventTypeObj?.writeList || this.initData.eventTypeList || []
    }
  },

  async mounted() {
    this.getAuthByRootInitData()
    this.getEnabledEventCardList()
    const that = this
    window.onresize = () => {
      return (() => {
        that.navWidth = window.innerWidth - 120;
      })();
    };

    /** * 校验事件 */
    try {
      let eventCalendar = await EventApi.calendarEventShow();
      this.eventPlanningBtn = eventCalendar.data;
    } catch (error) {
      console.warn(error);
    }

    // 获取缓存的pagesize
    const localStorageData = await this.getLocalStorageData();
    this.searchParams.pageSize = localStorageData[EVENT_PAGE_SIZE_KEY] || 10;
    this.filterConfig = getFilterConfig().filter(config => {

      // 纯客服云版本不显示创建工单
      if (config.name == 'isTransferToTask') {
        return this._isShowTaskModule;
      }

      return config
    }) // 事件状态/创建视角/事件类型/创建工单等筛选配置的初始化
    await this.initialize() // 获取初始化数据
    this.search()
    
    // 对外开放刷新方法，用于其他tab刷新本tab数据
    window.__exports__refresh = async () => {
      this.refreshPage();
    }
    
    /* 检查是否还有物流剩余次数 */
    this.checkQuota()
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
  },
  methods: {
    // 批量导出附加组件 Start
    getEnabledEventCardList() {
      EventApi.getEnabledEventCardList()
        .then(res => {
          if (res.succ) {
            this.eventCardList = res.data
          }
        })
    },
    exportAdditional(item){
      this.$refs.statistical.openDialog(item)
    },
    // 批量导出附加组件 End

    async fetchTypeList() {
      try {
        const { succ = true, status, data  } = await EventApi.getServiceEventTypeList()
        if(succ) {
          this.eventTypeObj = data
        }
      } catch(e) {
          console.error('【fetch EventApi.fetchTypeList error】', e)
      }
    },
    /**
     * @description: 获取事件满意表单字段
     */    
    getSatisfactionFields() {
      EventApi.satisfactionFields({templateId:this.currentEventType?.id || ''}).then(res => {
        const { code, result} = res;
        if(code == 0) {
          result.forEach((field) => {
            field.group = 'event';
            field.label = field.displayName;
            field.field = field.fieldName;
          });
          this.satisfactionFields = res.result || [];
        }
      });
    },

    // 获取服务事件列表
    queryEventPageList(params = {}) {
      const query = { "isOrderList" : false }
      this.loading = true
      this.isFetchEventPageEnd = false
      EventApi.queryEventPageList(query, params)
        .then(res => {
          if(res.succ && res.status == 0) {
            this.originEventPage = cloneDeep(res.data)
            if(res.data){
              res.data.list = disposeFormListViewTime((res.data.list || []), this.columns)
            }
            this.eventPage = res.data || {}
            // TODO 匹配选中的数据
            setTimeout(()=>{
              this.$nextTick(() => {
                this.matchSelected()
              })
            }, 500)
          }
        })
        .catch(err => { console.error(err) })
        .finally(() => { 
          this.loading = false 
          this.isFetchEventPageEnd = true
        })
    },
    // 把选中的匹配出来
    matchSelected(data) {
      if (this.multipleSelection.length) {
        this.eventPage.list.forEach(item => {
          if(this.multipleSelection.some(v=> item.id === v.id)){
            this.$refs.table.toggleRowSelection(item,true);
          }
        });
      }
    },

    // 初始化事件类型筛选项
    async initEventTypeField(eventTypeList) {
      await this.fetchTypeList()
      
      const replaceTypeList = this.eventTypeObj?.readList || eventTypeList || []

      const typeList = replaceTypeList.map(item => {
        return {
          label: item.name,
          value: item.id,
          active: false
        }
      })
      // TODO 类型的赋值
      const defaultContent = [{
        label: this.$t('common.base.all'),
        value: 'all',
        active: true
      }]
      this.filterConfig[2].content = [...defaultContent, ...typeList]
    },
    getAbnormalText() {
      try {
        const abnormalData = []
        getExceptionFields()[0] && (getExceptionFields()[0].content || []).forEach(item => {
          if(item.label !== '全部') abnormalData.push(item.label)
        })
        this.abnormalText = abnormalData.toString()
      } catch (error) {
        console.error(error)
      }
    },

    // 初始化处理事件状态--拼接对应状态的数量
    initEventStatusField(stateCount) {
      const totalValueArr = Object.values(stateCount)
      const totalCount = totalValueArr.reduce((tole, value) => {
          return tole + value;
      });
      const { finished=0,  allFinished=0, convert2Task=0 } = stateCount
      stateCount.allFinished = finished + allFinished + convert2Task
      this.filterConfig[0].content.forEach((item, index) => {
        if(stateCount[item.value]) {
          item.count = item.value ? stateCount[item.value] : 0
        } else {
          if(item.value === 'all') {
            item.count = totalCount - stateCount['exception'] // 全部事件总和需去掉异常事件
          }
        }
      })
    },

    // 搜索
    search() {
      this.$nextTick(()=>{
        // 滚动至表格顶部
        this.$refs.table?.$refs?.bodyWrapper?.scrollTo(0, 0)
      })
      const searchParams = this.buildSearchParams()
      this.visible = false;
      this.queryEventPageList(searchParams)
    },

    // 构建搜索参数
    buildSearchParams() {
      let advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      const {customerId, tlmId, productId, conditions} = advancedSearchParams;
       
      return {
        ...this.searchParams,
        ...advancedSearchParams,
        conditions,
        cusId: customerId || '',
        lmId: tlmId || '',
        productId: productId || '',
      }
    },

    // 重置
    resetParams() {
      window.location.reload()
    },

    // 高级搜索
    panelSearchAdvancedToggle() {
      this.visible = true;
    },

    /**
     * @description: 筛选项点击事件
     * @param {String} parent 父节点信息
     * @param {String} current 当前筛选数据
     */
    handleFilterClick(parent, current, searchNow = true) {
			this.$track.clickStat(this.$track.formatParams('QUICK_SEARCH', parent.label))
			
      return new Promise((resolve, reject)=>{
        parent.content.forEach(item => {
          item.active = false
          if(item.value === current.value) {
            item.active = true
          }
        });
        const currentValue = current.value == 'all' ? '' : current.value 
        // 异常事件 插入异常筛选项
        if(parent.name === 'state') {
          if (currentValue === 'exception') {
            // 如果不存在异常筛选项再插入异常筛选项
            if(!this.filterConfig.some(item => item.name == 'exceptionType')){
              this.filterConfig = [...this.filterConfig, ...getExceptionFields()]
            }
          } else {
            this.filterConfig = this.filterConfig.filter(item => {
              return item.name !== 'exceptionType'
            })
          }
          this.currentEventStatus = current
          this.initialize(true);
        }
        this.searchParams[parent.name] = currentValue
        if(parent.name === 'templateId') { // 点击事件类型
          const currentObj = {
            name: current.label,
            id: currentValue
          }
          this.currentEventType = current.value == 'all' ? {} : currentObj
          this.initialize(true);
          // 切换事件类型时需要初始化高级搜索表单 保留系统字段 初始化自定义字段的值
          this.$refs.searchPanel && this.$refs.searchPanel.initEventFormVal();
        }
        resolve();
        if(searchNow){
          this.resetSearch();
        }
      })
      
    },
    resetSearch(){
      this.searchParams.pageNum = 1;
      this.search()
    },
    // 新建按钮下拉列表点击事件
    toCreateEvent({id}) {
			this.$track.clickStat(this.$track.formatParams('TO_CREATE'));
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: 'createEvent',
      //   title: '新建事件',
      //   url: `/event/edit?defaultTypeId=${id}`,
      //   close: true,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateEvent,
        params: `defaultTypeId=${id}`,
        fromId
      })
    },

    //  批量编辑
    handleAllotEdit() {
      const { selectedIds, currentEventType, eventTemplateFields } = this;
      if (!currentEventType.id) {
        this.$message({
          message: this.$t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.tips2'),
          type: 'warning'
        });
        return;
      }
      if (!selectedIds.length) {
        this.$message({
          message: this.$t('event.eventOrderList.text5'),
          type: 'warning'
        });
        return;
      }
      this.$refs.eventBatchEditDialog.open();
    },

    // 保存编辑
    updateEdit() {
      this.search()
    },

    // 删除
    async handleDelete() {
      const { selectedIds } = this;
      if (!selectedIds.length) {
        this.$message({
          message: this.$t('event.eventOrderList.text6'),
          type: 'warning'
        });
        return;
      }

      this.$confirm(this.$t('event.eventOrderList.text7'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(async () => {
          const { succ } = await EventApi.eventDelete(selectedIds);
          if (succ) {
            this.$message({
              message: this.$t('common.base.deleteSuccess'),
              type: 'success'
            });
            this.toggleClearSelection()
            this.refreshPage()
          }
        })
        .catch(() => { });
    },

    /**
     * @description: 
     * @param {Object} item 选中事件类型
     * @param {Boolean} isExist 是否现有客户
     */
    importEvent(item, isExist) {
      this.checkedImportEvent = item
      this.eventImportExist = isExist

      this.eventImportAction = `${eventListImport_1}/${isExist ? 'exist' : 'notExist' }?typeId=${item.id}`
      this.eventImportTemplateUrl = `${eventListImportTem_1}?way=${isExist ? '1' : '2' }&typeId=${item.id}`

      this.$nextTick(() => {
        this.$refs.importCustomerModal.open();
      })
    },

    /**
     * @description: 导出（全部）
     * @param {Boolean} isExportAll 是否导出全部
     */
    async handleExport(isExportAll) {
      let ids = [];
      let fileName = formatDate(safeNewDate(), 'YYYY-MM-DD') + this.$t('event.list.text1') + '.xlsx';
      if (!isExportAll) {
        if (!this.multipleSelection.length) {
          this.$message({
            message: this.$t('common.base.tip.exportNoChoice'),
            type: 'warning'
          });
          return;
        };
        ids = this.selectedIds;
      }

      const ExportPanelComponent = this.$refs.exportPanel
      if (!ExportPanelComponent) {
        return console.warn('Caused: $refs.exportPanel is Empty')
      }

      const LocalStorageData = await this.getLocalStorageData()
      let exportCheckedData = LocalStorageData.exportCheckedData

      if (!exportCheckedData) {
        exportCheckedData = {
          checkedGroup: [],
          checkedMap: {},
          isCheckedAll: false,
          tooltip: true
        }
      }

      ExportPanelComponent.open(ids, fileName, false, exportCheckedData)
    },

    /**
     * 下载附件
     */
    async exportAttachment(){
      const { multipleSelection, $platform, $message } = this;
      if(!multipleSelection.length){
        return $platform.alert(this.$t('task.tip.taskListTip8'));
      }
      try{
        const eventIds = multipleSelection.map(item=>item.id);
        let { status, message } = await EventApi.exportAttachment({eventIds});
        // $message({
        //   type:`${ status === 0 ? 'success' : 'error'}`,
        //   message
        // });
        // $platform.alert(message);
        // if(status === 0){
        //   window.parent.showExportList();
        //   window.parent.exportPopoverToggle(true);
        // }
        if(status === 0){
          showExportListAlert(message)
        }else {
          $platform.alert(message);
        }
      }catch(err){
        console.error('下载事件附件 error:', err);
      }
    },

    // 事件转发
    handleEventReAllot() {
      const { selectedIds } = this;
      if (!selectedIds.length) {
        this.$message({
          message: this.$t('event.eventOrderList.text8'),
          type: 'warning'
        });
        return;
      }
      this.$refs.eventBatchReAllotDialog.open()
    },

    async initialize(isEventStatus) {
      // 清除导出配置的缓存
      localStorage.removeItem('checkedMap')
      localStorage.removeItem('checkedGroupArr')
      localStorage.removeItem('isCheckedAll')

      let query = { "isOrderList" : false }
      const params = { "pageSize" : 10 , "templateId": this.currentEventType?.id || ''}

      if(!this.currentEventType?.id) {
        query.isAllTemplate = true;
      }

     if(this.customerSatisfaction) {
        await this.getSatisfactionFields();
      }

      await EventApi.queryEventPageInfo(query, params)
        .then(async res => {
          if(res.status == 0 && res.succ) {
            let { allEventFields=[], evaluateConfig={}, cardDetailList=[], eventTypeList=[], stateCount=[], eventAllotHasSub} = res.data
            
            if(!isEventStatus) {
              // TODO 类型的赋值
              this.initData = res.data
              if(!this.initData.serviceStationEnabled) {
                this.$message.error(this.$t('event.eventOrderList.text9'));
                return
              }
              this.hasSub = Number(eventAllotHasSub)
              this.initEventTypeField(eventTypeList) // 处理事件类型
              this.initEventStatusField(stateCount) // 处理事件状态对应数量
              this.getAbnormalText() // 获取异常节点文本
            }

            // 点击全部的时候过滤下不要自定义字段
            if(!this.currentEventType?.id) {
              // 处理选择全部时的自定义字段
              const customFields = smoothLogisticsField(_.cloneDeep(allEventFields))
              this.allCustomFields = this.handlerCustomFields(customFields);
              allEventFields = allEventFields?.filter(item => item.isSystem != 0)
            }

            let originAllFields = _.cloneDeep(allEventFields)
            let newAllEventFields = smoothLogisticsField(allEventFields)
            this.originAllFields = originAllFields
            this.formatAllEventFields(newAllEventFields) // 事件类型&事件类型回执字段处理
            this.getExtraAdvanceSearchFields(originAllFields) // 获取额外的高级搜索字段
            await this.buildColumns(); // 构建表格/选择列字段
            this.buildExportColumns(cardDetailList, evaluateConfig) // 构建导出字段
            this.findFastPageData();
            window.addEventListener('message', (event)=> {
              const {action, data} = event.data;
              if (action == 'shb.frame.fasterPage'){
                const {data:parseData, type} = data;
                if(type == `bbx-faster-${pageEventList.type}`){
                  this.findFastPageData(parseData);
                }
              }
            });

            this.$nextTick(()=> {
              this.knowTableContainerHeight()
              let that_ = this;
              window.onresize = _.debounce(()=>{
                that_.knowTableContainerHeight()
                that_.navWidth = window.innerWidth - 120;
              }, 500)
            })
          } else {
            this.columns = this.eventListFields // 初始化先给表格一个默认配置 骨架屏的作用
          }
        })
        .catch((err) => {
          console.error(err)
          this.columns = this.eventListFields
        })
        .finally(() => {
          
          if (!this.isFetchEventPageEnd) {
            return
          }
          
          this.$nextTick(() => {
            let originEventPage = cloneDeep(this.originEventPage) || {}
            let originEventPageList = originEventPage.list || []
            originEventPage.list = disposeFormListViewTime(originEventPageList, this.columns)
            this.eventPage = originEventPage
          })
          
        })
    },

    // 通过pageinfo获取事件类型&回执字段 并做处理
    formatAllEventFields(allEventFields) {
      const eventTemplateFields = []
      const eventTemplateReceiptFields = []
      allEventFields.forEach((field) => {
        field.group = field.tableName;
        field.label = field.displayName;
        field.field = field.fieldName;
        if(field.formType === 'date' || field.formType === 'datetime') {
          field.sortable = 'custom'
        }
        if(field.tableName === 'event') {
          eventTemplateFields.push(field)
        } else if(field.tableName === 'eventReceipt') {
          eventTemplateReceiptFields.push(field)
        }
      });
      this.$set(this, 'eventTemplateFields', eventTemplateFields || []);
      this.$set(this, 'eventTemplateReceiptFields', eventTemplateReceiptFields || []);
    },

    // 获取额外的高级搜索字段
    getExtraAdvanceSearchFields(allEventFields) {
      this.extraAdvanceFields = allEventFields.filter(field => {
        return field.isSearch == 1 && field.isSystem == 0
      })
    },
    
    // 构建列表项
    async buildColumns() {
      // 获取缓存在本地的选择列配置
      const localStorageData = await this.getLocalStorageData();
      let columnStatus = localStorageData[this.EVENT_COLUMNS_KEY] || [];
      if(Array.isArray(columnStatus) && !columnStatus.length){
        columnStatus = await getServerCach(this.EVENT_COLUMNS_KEY, [], 'event', this.EVENT_COLUMNS_KEY) || []
      }
      const localColumns = columnStatus
        .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          }
          return acc
        }, {});

      let eventListFields = this.eventListFields // 本地默认的表格项字段
      const { evaluateConfig={} } = this.initData
      if(this.customerSatisfaction) {
        if(this.satisfactionFields.length > 0 ) {
          eventListFields = eventListFields.concat(this.satisfactionFields)
        }
      }else {
        if(evaluateConfig.useStarEvaluate) { // 如果有服务标签等 构建额外的服务评价列表项
          eventListFields = eventListFields.concat(this.buildExtraEvaluateColumns())
        }
      }

      let fields = eventListFields.concat(this.eventTypeFilterFields); // 拼接不同【事件类型】对应的表格项字段

      if (Array.isArray(columnStatus) && columnStatus.length > 0) { // 有本地缓存--列表排序
        fields = this.buildSortFields(fields, localColumns)
      }
      
      const columns =  fields.map((col) => { // 选择列配置 是否勾选（显示）&宽度
        let show = col.show;
        let width = col.width;
        let localField = localColumns[col.field]?.field || null;

        if (null != localField) {
          if (localField.width) {
            width = typeof localField.width == 'number'
              ? `${localField.width}px`
              : localField.width;
          }
          show = localField.show !== false;
        } 

        col.show = show;
        col.width = width;
        col.minWidth = col.width || 150;
        col.type = 'column';
        return col;
      }).filter(f => f.formType !== 'attachment' && f.formType !== 'separator' && f.formType !== 'info' && f.formType !== 'autograph' && f.formType !== FieldTypeMappingEnum.JsCodeBlock);

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice())
      })
    },

    // 选择列排序
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = []

      originFields.forEach(originField => {
        let { fieldName } = originField
        let field = fieldsMap[fieldName]

        if (field) {
          let { index } = field
          fields[index] = originField
        } else {
          unsortedFields.push(originField)
        }
      })

      return fields.concat(unsortedFields)
    },

    // 构建导出项
    buildExportColumns(cardDetailList, evaluateConfig) {
      // 事件信息
      const eventInfo = {
        label: this.$t('event.eventOrderList.text10'),
        value: 'eventChecked', // 本应该为eventChecked or eventReceiptChecked 但是批量导出组件对多行数据的判断写死了，暂时先这么写
        columns: this.formatExportEventInfo(false),
      }
      // 完成回执信息
      const eventReceiptInfo = {
        label: this.$t('event.eventOrderList.text11'),
        value: 'eventReceiptChecked',
        columns: this.formatExportEventInfo(true),
      }
      // 附加组件
      const cardDetailInfo = this.formatExportCardDetailInfo(cardDetailList);
      // 系统信息
      const systemInfo = {
        label: this.$t('common.task.TaskExportGroupTextEnum.system'),
        value: 'systemChecked',
        columns: getExportSystemInfo().map(item => {
            item.export = true
            item.label = item.displayName
            return item
          }).filter(f => {
            // 纯客服云版本不显示是否创建工单、关联工单
            if (['isTransferToTask', 'taskNo'].includes(f.exportAlias)) {
              return this._isShowTaskModule
            }

            return f
          })
      }
      // 评价信息
      const evaluateInfo = {
        label: this.$t('common.form.fieldGroupName.customerSatisfaction'),
        value: 'evaluateChecked',
        columns: this.formatExportEvaluteInfo(evaluateConfig),
      }
      // 导出子表单
      const eventSubFormFieldList = []
      this.originAllFields.forEach(item => {
        if(item?.setting?.isSubForm && (item.subFormFieldList && item.subFormFieldList.length > 0)) {
          let columns = item.subFormFieldList || []
          columns.forEach(sub => {
            sub.value = sub.fieldName
            sub.label = sub.displayName
            sub.field = sub.fieldName
            sub.export = true
          })

          eventSubFormFieldList.push({
            value: item.fieldName,
            label: item.displayName,
            columns
          })
        }
      })

      this.exportColumnList = [eventInfo, eventReceiptInfo, ...cardDetailInfo, systemInfo, evaluateInfo,...eventSubFormFieldList].filter(item => {
        return item.columns && item.columns.length > 0
      })
      // console.log("exportColumnList", JSON.stringify(this.exportColumnList))
    },

    /**
     * @description: 处理导出--事件信息&回执信息
     * @param {Boolean} isReceipt 是否回执
     */
    formatExportEventInfo(isReceipt) {
      let eventInfo = []
      const info = isReceipt ? this.eventTemplateReceiptFields : this.eventTemplateFields
      eventInfo = info.filter(item => {
        return item.formType !== 'attachment'&& item.formType !== 'separator' && item.formType !== 'info' && item.formType !== 'autograph' && item.formType !== FieldTypeMappingEnum.JsCodeBlock && item.formType !== 'systemAutograph'
      })
      if(!isReceipt) { // 如果是事件信息
        const fullEventInfo = []
        eventInfo.forEach((item, index) => {
          fullEventInfo.push(item)
          if(item.fieldName=='eventNo') {
            fullEventInfo.push({
              'fieldName': 'templateName',
              'displayName': this.$t('customer.detail.customerEventTable.table.label.templateId')
            })
          }
          if (item.fieldName=='customer') {
            const customerOption = item?.setting?.customerOption || {}
            const customerArr = [
              {
                fieldName: 'customerLinkman',
                displayName: this.$t('common.base.contact'),
                show: customerOption.linkman

              },
              {
                fieldName: 'customerPhone',
                displayName: this.$t('common.base.phone'),
                show: customerOption.linkman
              },
              {
                fieldName: 'customerAddress',
                displayName: this.$t('common.base.locationMap.customerAddress'),
                show: customerOption.address
              },
              {
                fieldName: 'product',
                displayName: this.$t('common.base.product'),
                formType : 'select',
                show: customerOption.product,
                setting: {
                  isMulti: true
                }
              }
            ]
            customerArr.forEach(cItem => {
              cItem.show && fullEventInfo.push(cItem)
            })
          }
        })
        eventInfo = fullEventInfo
      }
      eventInfo.map(item => {
        item.exportAlias = item.fieldName
        item.label = item.displayName
        item.export = true
        return item
      })
      return eventInfo
    },

    // 处理导出--附加组件
    formatExportCardDetailInfo(cardDetailList = []) {
      let list = cardDetailList.filter(item => item && item.specialfrom !== '连接器').map((item, index) => {
        if (item.canRead) {
          let columns = []
          item.fields = [
              ...item.fields, 
              ...[
                { displayName: this.$t('common.base.operator'), fieldName: `cu_${item.cardId}`},
                {displayName: this.$t('common.label.operationTime'), fieldName: `ct_${item.cardId}`}
              ]
            ]
          columns = item.fields.map((v, i) => {
            return {
              export: item.canRead,
              label: v.displayName,
              exportAlias: v.fieldName,
              ...v,
            };
          }).filter(v => {
            return v.formType !== 'attachment'&& v.formType !== 'separator' && v.formType !== 'info' && v.formType !== 'autograph'
          });
          return {
            value: `annexChecked${index}`,
            label: this.$t('event.eventOrderList.text13', {data1: item.cardName}),
            inputType: item.inputType,
            columns,
          };
        }
      }).filter(item => {
        if (item) {
          return item
        }
      })
      return list
    },

    // 处理导出--评价信息
    formatExportEvaluteInfo(evaluateConfig) {
      // 满意度开启的导出数据去满意度处理
      let satisfactionFields = [];
      if(this.customerSatisfaction) {
        this.satisfactionFields.map(field => {
          field.export = true
          field.label = field.displayName
          field.exportAlias = field.fieldName
          satisfactionFields.push(field) 
        })

        return satisfactionFields;
      }

      let starEvaluates = []
      if(evaluateConfig.useStarEvaluate) {
        starEvaluates = _.cloneDeep(evaluateConfig.starEvaluates)
      }
      if (evaluateConfig.useTagEvaluate) {
        // TODO: 下面有判断，需要确认下
        starEvaluates.push(this.$t('common.customer.questionnaire.serviceTag'))
      }
      
      const configInfo = starEvaluates.map((item,index) => {
        return {
          exportAlias: item === this.$t('common.customer.questionnaire.serviceTag') ? 'tagEvaluates' : `starEvaluate${index+1}`,
          label: item,
          export: true
        }
      })
      return configInfo
    },
  
    // 打开选择列
    showAdvancedSetting() {
      this.$refs.advanced.open(this.columns, this.currentEventType);
    },
    
    /**
     * @description 表头更改
     */
    headerDragend (newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },

     /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus (event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },

    // 保存选择列配置
    saveColumnStatus(event) {
      let columns = event.data || []

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage()
      })
      this.$message.success(this.$t('common.base.saveSuccess'));
    },

    // 保存选择列配置到本地
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.field,
        show: c.show,
        width: c.width,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }
      setServerCach(this.EVENT_COLUMNS_KEY, columnsStatus, 'event', this.EVENT_COLUMNS_KEY)
      this.saveDataToStorage(this.EVENT_COLUMNS_KEY, columnsStatus);
    },

    /**
     * @description 获取行的key
     * @param {Object} row 行数据
     * @return {String} key
     */
    getRowKey(row = {}) {
      return row.id;
    },

    // 清空选择框
    toggleClearSelection() {
      this.multipleSelection = [];
      this.$refs.table.clearSelection();
    },

    // 表格选择操作
    handleSelection(selection) {
      this.multipleSelection = this.selectionCompute(selection);
    },
        /**
     * @description 计算已选择
     * @param {Array} selection 已选择列表
     * @return {Array} 计算过滤后的列表
     */
    selectionCompute(selection) {
      let tv = [];

      tv = this.multipleSelection.filter((ms) =>
        this.eventPage.list.every((c) => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },

    // 排序变化
    sortChange(option) {
      const {column, order, prop} = option;
      const sortedField = this.columns.filter((item) => item.fieldName === prop)[0] || {};
      if(column === null) {
        this.searchParams.orderDetail = {};
      }else{
        this.searchParams.orderDetail = {
          column: sortedField.sortName || sortedField.fieldName,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          type: sortedField.dataType || sortedField.formType,
          isSystem: sortedField.isSystem,
        }
      }
      this.search();
    },

    // 页码跳转
    jump(pageNum) {
      this.searchParams.pageNum = pageNum;
      this.eventPage.list = [];
      this.search();
    },

    // 页大小改变
    handleSizeChange(pageSize) {
      this.saveDataToStorage(EVENT_PAGE_SIZE_KEY, pageSize);
      this.searchParams.pageSize = pageSize;
      this.searchParams.pageNum = 1;
      this.search();
    },

    // 设置高级搜索展示列数
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },

    // 构建导出参数
    buildExportParams(checkedMap, ids, exportOneRow) {
      const {
        eventReceiptChecked,
        systemChecked,
        eventChecked,
        evaluateChecked,
      } = checkedMap
      
      let exportAll = !ids || !ids.length;

      const exportSearchModel = { 
        ...this.buildSearchParams(),
        exportTotal: exportAll ? this.eventPage.total : this.selectedIds.length,
      }

      let params = {
        isOrder: false,
        typeId: this.currentEventType.id,
        exportSearchModel: JSON.stringify(exportSearchModel)
      };
      
      // 附加
      let cardFieldChecked = []
      for (let key in checkedMap) {
        if (key.indexOf('annexChecked') !== -1) {
          cardFieldChecked = [...cardFieldChecked, ...checkedMap[key]]
        }
      }
      cardFieldChecked = cardFieldChecked.filter(item => {return item})
      /** ********************* *********************/
      // 事件信息
      let export_checked = this.exportData('eventChecked', eventChecked)
      // 回执信息
      let export_receipt = this.exportData('eventReceiptChecked', eventReceiptChecked)
      // 系统信息
      let export_sys = this.exportData('systemChecked', systemChecked)
      // 评价信息
      let export_evaluate = this.exportData('evaluateChecked', evaluateChecked)
      // 附加信息
      let export_card_field = cardFieldChecked.length ? this.exportData('cardFieldChecked', cardFieldChecked) : cardFieldChecked
      // 子表单
      let export_subFields = this.buildSubExportData(checkedMap)
      // 过滤掉子表单中存在的key
      export_checked = this.filterChecked(export_checked,export_subFields)
      params['exportOneRow'] = exportOneRow
      params['data'] = exportAll ? '' : this.selectedIds.join(',');
      params['receiptChecked'] = export_receipt.join(',');
      params['sysChecked'] = export_sys
        .map((item) => {
          return item;
        })
        .join(',');
      params['evaluateChecked'] = export_evaluate
        .map((item) => {
          return item;
        })
        .join(',');
      params['checked'] = export_checked
        .map((item) => {
          if (item === 'product') {
            item = 'product,productSN'
          }
          return item;
        })
        .join(',');
      params['cardFieldChecked'] = export_card_field.filter(item => {
        return item
      }).join(',') 
      params['subFieldNameMap'] = export_subFields;
      return params;
    },
    /**
     * 导出子表单数据
     */
    buildSubExportData(checkedMap) {
      try{
        let subFields = this.originAllFields.filter(v=>v.formType === 'relationForm').map(item => item.fieldName);
        if(!subFields.length) return {}
        const tempData = {}
        subFields.map(v=>{
          tempData[v] = checkedMap[v]
        })
        return tempData
      }catch(err){
        console.log(err)
        return {}
      }
    },
    filterChecked(data, fields) {
      try {
        let keys = Object.keys(fields)
        return data.filter(v => {
          return keys.every(v2 => v2 != v)
        })
      } catch (err) {
        console.log(err)
        return data
      }
    },
    /**
     * 导出数据
     */
    exportData(type, list = []) {
      const export_list = this.exportColumnList
      if (type === 'cardFieldChecked') {
        let cardField = []
        export_list.filter((item, index) => {
          // 有待商榷
          return item.value !== 'eventChecked' && item.value !== 'eventReceiptChecked' && item.value!== 'systemChecked'
        }).forEach(v => {
          v.columns.forEach(item => {
            cardField.push(item)
          })
        })
        return cardField.map(v => {
          let bool = list.some(item => {
            if (v.exportAlias) {
              return v.exportAlias === item
            } 
            return v.fieldName === item
            
          })
          if (bool) {
            return v.exportAlias ? v.exportAlias : v.fieldName
          }
        }).filter(item => {
          return item
        })
      }

      let xlistColumns = []
      export_list.forEach((xlist, i) => {
        if(xlist.value === type) xlistColumns = xlist.columns
      })

      return xlistColumns.map(v => {
        let bool = list.some(item => {
          if (v.exportAlias) {
            return v.exportAlias === item
          } 
          return v.fieldName === item
          
        })
        if (bool) {
          return v.exportAlias ? v.exportAlias : v.fieldName
        }
      }).filter(item => {
        return item
      })
    },

    // 导出提示
    exportAlert(result, params = {}) {
      this.$notify({
        title: result.status === 0 ? this.$t('common.base.success') : this.$t('common.base.error'),
        message: result.message,
        type: result.status === 0 ? 'success' : 'error'
      });
    },

     /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.eventPage.total > max
        ? this.$t('common.base.tip.exportMostTip')
        : null;
    },

    // 打开or关闭订阅通知
    async toggleEventSubscribe() {
      let action = this.hasSub ? EventApi.eventUnSubscribe : EventApi.eventSubscribe;
      let tip = this.hasSub ? this.$t('common.base.tip.canceledSubscribeNotify') : this.$t('common.base.tip.subscribeNotify');
      try {
        let res = await action({module:'eventAllot'});
        if(res.status == 0){
          this.$message({
            message: tip,
            type: 'success'
          });
          this.hasSub = this.hasSub == 0 ? 1 : 0;
        }else {
          this.$message.error(res.message);
        }
      } catch (error) {
        console.error(error);
      }
    },

    // 获取本地localstorage
    getLocalStorageData() {
      const dataStr = storageGet(EVENT_LIST_KEY, '{}');
      return JSON.parse(dataStr);
    },

    // 保存数据到本地localstorage
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(EVENT_LIST_KEY, JSON.stringify(data));
    },

    // 单独获取事件状态对应的数量
    async queryEventStatusNum() {
      const query = { "isOrderList" : false }
      const params = { "pageSize" : 10 , "templateId": this.currentEventType?.id || ''}

      await EventApi.queryEventPageInfo(query, params)
        .then(res => {
          if(res.status == 0 && res.succ) {
            const {stateCount=[]} = res.data
            this.initEventStatusField(stateCount) // 处理事件状态对应数量
          }
        })
    },

    // 更新页面
    async refreshPage() {
      this.queryEventStatusNum()
      this.search()
    },

    /**
     * @description 获取显示最后一次更新记录
     * @param {Object} row 行数据
     */
    async fetchLastUpdateRecord(row) {
      // 存在历史更新记录
      if (row.lastUpdateRecord) {
        return console.warn(`Caused: ${row.taskNo} row have lastUpdateRecord`)
      }
      
      try {
        const result = await EventApi.getEventUpdateRecord({ eventId: row.id })
        const { succ, data } = result
        
        if (!succ) return

        this.eventPage.list.forEach(item => {
          if(item.id === row.id) {
            // 通过set方法去刷新数据更新视图，（下文tableKey使用随机key重新渲染表格的方式会导致表格选中状态消失。）
            this.$set(item, 'lastUpdateRecord', data)
          }
        })

        // 重新渲染表格以显示提示
        const ElementBodyHtmlElement = this.$el.querySelector('.el-table__body-wrapper') || {}
        const ElementBodyHtmlElementScrollLeft = ElementBodyHtmlElement.scrollLeft
        const PageScrollTop = this.$refs.eventPageRef.scrollTop

        // 更新key以重新更新渲染列表数据
        // this.tableKey = randomString()

        this.$nextTick(() => {
          // 有横向滚动条的时候，记住上次滚动的位置，不然每次重新渲染都会回到开头
          this.$el.querySelector('.el-table__body-wrapper').scrollLeft = ElementBodyHtmlElementScrollLeft
          // 有纵向滚动，记住上次位置，不然每次重新渲染都会回到开头（但是task list没有写这个没有问题，有空看一下）
          this.$refs.eventPageRef.scrollTop = PageScrollTop
        })
      
      } catch (error) {
        console.error(error)
      }
    },

    /**
     * @des 提供给快捷筛选视图的方法
     */
    fasterFilterList(keyObj){
      try {
        let arr_ = [];
        for(let key in keyObj){
          let value = keyObj[key]
          let parent = this.filterConfig.find(item=>item.name == key);
          let child = parent.content.find(item=>item.value == value);
          arr_.push(this.handleFilterClick(parent, child, false))
        }
        Promise.all(arr_).then(()=>{
          this.resetSearch();
        })
      } catch (error) {
        console.warn(error, 'fasterFilterList error try catch');
      }
    },
    /**
     * @des 查询是否有查询参数
     */
    findFastPageData(data){
      try {
        let parseData = sessionStorageGet(`bbx-faster-${pageEventList.type}`);
        if(parseData){
          sessionStorageRemove(`bbx-faster-${pageEventList.type}`);
        }
        if(!data && !parseData) return
        const {filterData} = data || JSON.parse(parseData);
        this.fasterFilterList(filterData);
      } catch (error) {
        console.warn(error, 'findFastPageData error try catch');
      }
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1  - 24 - 8 - 8 - 16;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        console.log(min, 'min')
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.batch-export-additional {
  max-height: 300px;
  overflow-y: auto;

}

.event-list {
  .search-input{
    width: 440px ;
  }
  
  >div {
    border-radius: 4px;
  }

  .common-list-view__v2 {
    padding-bottom:0;
    .operate-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .el-button:first-child {
        margin-left: 0;
      }
      >div {
        display: flex;
        align-items: center;
        .icon-ding-yue {
          font-size: 14px;
          &.actived {
            color: $color-primary-light-6;
          }
        }
      }
    }
  }
}
.import-event {
  position: relative;
  left: -15px;
  padding-left: 15px;

  &:hover &-item {
    display: block;
  }

  &-item, .import-event-item-children {
    position: absolute;
    background: #fff;
    color: #333;
    left: -115px;
    top: -1px;
    border: 1px solid #eee;
    border-radius: 4px;
    display: none;

    >div {
      padding: 4px 15px;
      width: 120px;
      position: relative;

      &:hover {
        background-color: $select-draggable-color;
        color: $color-primary-light-6;
      }
    }
  }

  &-item {
    top: -7px;
    >div:hover {
      .import-event-item-children {
        display: block;
      }
    }
  }
}

::v-deep .advanced-search-form {
  height: auto;
  padding: 10px 15px 15px 15px;
}
::v-deep .el-table__body {
  width: 100%;
}
</style>

<style lang="scss" scoped>
// 列表头部样式
.list-header {
  position: relative;
  // 头部搜索
  .list-header-search {
    padding: 16px;
    display: flex;
    border-radius: 4px 4px 0 0;
    .custom-view {
      flex: 0 0 140px;
    }
    .right-view {
      flex: 1;
      .searh-input-box {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }

      .advanced-search-btn {
        color: $color-primary-light-6;
        .iconfont{
          color: $color-primary-light-6;
        }
      }
    }
  }

  // 头部筛选
  .list-header-nav {
    padding: 0 16px 16px;
    border-radius: 0 0 4px 4px;
    .filter-tab-box {
      display: flex;
      flex-direction: column;
      .filter-tab__item {
        display: flex;
        align-items: flex-start;
        .filter-tab__label {
          padding-top: 4px;
          width: 90px;
          min-width: 90px;
          font-weight: 500;
          color: #a7b5b5;
        }
        .filter-tab__content {
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          position: relative;
          overflow: hidden;
          .content-item{
            font-size: 13px;
            overflow-y: hidden;
            color: grey;
            .content-item-label {
              padding: 4px 8px;
              border: 1px solid transparent;
              margin: 0 12px 8px 0;
              cursor: pointer;
              &:hover{
                color:$color-primary-light-6!important;
              }
              &.actived{
                background: $color-primary-light-1;
                border-radius: 4px;
                border: 1px solid $color-primary-light-2;
                color:$color-primary-light-6!important;
              }
            }
          }
          .element-icon{
            position: absolute;
            align-self: flex-start;
            right: 12px;
            top: 3px;
            span{
              font-size: 12px;
            }
          }
          &-pad{
            padding-right: 50px;
          }
        }
      }
    }
  }

  .open-nav-control {
    position: absolute;
    left: 50%;
    top: 100%;
    transform: translateX(-50%);
    width: 48px;
    height: 10px;
    background: linear-gradient(180deg,#fff,#f4f4f4);
    box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12);
    border-radius: 0 0 3px 3px;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    .iconfont{
      font-size: 10px;
      color: #4e4e4e;
      cursor: pointer;
    }
  }
}
.event-type-dropdown-group {
  display: flex;
  flex-flow: column;
  max-height: 70vh;
  overflow: auto;
}
</style>

<style lang="scss">
.event-list.common-list-container__v2 {

  .list-header-nav {
    
    .filter-tab__content {
      
      .content-item {
        
        max-width: 160px;
        @include text-ellipsis();
        
        span {
          display: inline-block;
          max-width: 100%;
          @include text-ellipsis();
        }
        
      }
      
    }
    
  }
  
}
</style>